package com.OnTimeTeam.OnTime;


import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class AddToFavoritesAsyncTask extends AsyncTask<String, Void, Boolean> {

    private Toast resultToast;
    private TextView textMessage;
    private ImageButton favoritesStar;
	private Context host;
	private String address;
	private boolean contextType;
	
	public AddToFavoritesAsyncTask(Context host, ImageButton favoritesStar, Toast resultToast, TextView textMessage, String address, boolean contextType) {
		
		this.host = host;
		this.address = address;
		this.contextType = contextType;
		this.favoritesStar = favoritesStar;
		this.resultToast = resultToast;
		this.textMessage = textMessage;

	}
	
    protected Boolean doInBackground(String... params) {//In Background
    	
		List<Address> geoResults = null;
		
		try {
			Geocoder geocoder = new Geocoder(host, Locale.getDefault());
			geoResults = geocoder.getFromLocationName(address, 1);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	    if (geoResults == null || geoResults.size() == 0)
	    	return false;
    	
    	return true;
    }      

    protected void onPreExecute() {//Before
    	super.onPreExecute();
    	
    	favoritesStar.startAnimation(AnimationUtils.loadAnimation(host, R.anim.rotate_left_2));
    	
    }
    
    protected void onPostExecute(Boolean result) {//After

    	favoritesStar.clearAnimation();
    	
    	if(result) {
    		if(contextType)
    			((SetSmart)host).postAdditionToFavorites(resultToast, textMessage);
    		else
    			((DefaultsSetter)host).postAdditionToFavorites(resultToast, textMessage);
    	}
    	else {
			textMessage.setText(host.getResources().getString(R.string.theAddress) + " " + address + " " + host.getResources().getString(R.string.isInvalid));
    		resultToast.show();
    	}

    }
	
    protected void onProgressUpdate(Void... values) {
    	
    	
    }
}

